<template>
  <div class="asset-overview-layout">
    <div class="overview-left">
      <div class="overview-item total-assets">
        <div class="title">资产概览</div>
        <div class="big-pie-chart" ref="bigPieRef"></div>
        <div class="big-pie-legend">
          <div class="legend-row">
            <span
              v-for="(item, idx) in assetPieData.slice(0, 2)"
              :key="item.name"
              class="legend-item"
            >
              <span
                class="legend-dot"
                :style="{ background: colorArr[idx] }"
              ></span>
              {{ item.name }} {{ item.value }}
            </span>
          </div>
          <div class="legend-row">
            <span
              v-for="(item, idx) in assetPieData.slice(2, 4)"
              :key="item.name"
              class="legend-item"
            >
              <span
                class="legend-dot"
                :style="{ background: colorArr[idx + 2] }"
              ></span>
              {{ item.name }} {{ item.value }}
            </span>
          </div>
        </div>
      </div>
    </div>
    <div class="overview-right">
      <div class="overview-grid">
        <div class="overview-item gauge" v-for="g in gaugeList" :key="g.key">
          <div class="title">{{ g.title }}</div>
          <div class="gauge-chart" :ref="(el) => (gaugeRefs[g.key] = el)"></div>
          <div class="gauge-legend">
            <span
              v-for="(item, idx) in g.data"
              :key="item.name"
              class="legend-item"
            >
              <span
                class="legend-dot"
                :style="{ background: colorArr[idx] }"
              ></span>
              {{ item.name }} {{ item.value }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  topInfo: {
    type: Object,
    default: () => ({}),
  },
});

// mock 数据
const assetData = {
  totalAssets: 385,
  vacantRate: "12%",
  vacantTotal: 12,
};

// 统一颜色数组
const colorArr = ["#546fc6", "#90cc76", "#FBBF24", "#ed6663"];

const assetPieData = [
  { name: "房屋资产", value: 0, key: "fw" },
  { name: "土地资产", value: 0, key: "td" },
  { name: "车位资产", value: 0, key: "cw" },
  { name: "其他资产", value: 0, key: "qt" },
];

const gaugeList = ref([
  {
    key: "rental",
    title: "价格比对预警",
    data: [
      { name: "评估价格", value: 0, key: "pinggu" },
      { name: "线上价格", value: 0, key: "xianshang" },
      { name: "线下价格", value: 0, key: "xiaxian" },
    ],
  },
  {
    key: "contract",
    title: "合同合规预警",
    data: [
      { name: "房屋合同", value: 0, key: "fw" },
      { name: "土地合同", value: 0, key: "td" },
      { name: "车位合同", value: 0, key: "cw" },
      { name: "其他合同", value: 0, key: "qt" },
    ],
  },
  {
    key: "vacancy",
    title: "空置监测预警",
    data: [
      { name: "房屋资产", value: 0, key: "fw" },
      { name: "土地资产", value: 0, key: "td" },
      { name: "车位资产", value: 0, key: "cw" },
      { name: "其他资产", value: 0, key: "qt" },
    ],
  },
  {
    key: "file",
    title: "文件缺失分析",
    data: [
      { name: "招标文件", value: 0, key: "zb" },
      { name: "合同文件", value: 0, key: "ht" },
      { name: "评估文件", value: 0, key: "pg" },
    ],
  },
]);

const gaugeRefs = {};
const bigPieRef = ref(null);

function getPieOption(
  dataArr,
  showCenter = false,
  centerText = "",
  color = colorArr
) {
  return {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    color,
    // legend: { show: false },
    graphic:
      showCenter && centerText
        ? [
            {
              type: "text",
              left: "center",
              top: "center",
              style: {
                text: centerText,
                textAlign: "center",
                fill: "#222",
                font: 'bold 22px "Microsoft YaHei"',
              },
            },
          ]
        : undefined,
    series: [
      {
        type: "pie",
        radius: showCenter ? ["50%", "90%"] : "90%",
        center: ["50%", "50%"],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: "inside",
          fontSize: showCenter ? 12 : 10,
          formatter: "{d}%",
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: "#fff",
          borderRadius: 2,
        },
        labelLine: {
          show: false,
        },
        data: dataArr.map((item) => ({
          value: item.value,
          name: item.name,
        })),
      },
    ],
  };
}
// 处理资产类型数据
const processAssetTypeData = (data) => {
  if (!data || !Array.isArray(data)) return;

  // 直接更新assetPieData的值
  data.forEach((item, index) => {
    if (assetPieData[index] && item.key === assetPieData[index].key) {
      assetPieData[index].value = item.value;
    }
  });

  // 计算总数
  const total = assetPieData.reduce((sum, item) => sum + item.value, 0);
  assetData.totalAssets = total;
};

// 处理右侧预警数据
const processWarningData = (data, type) => {
  if (!data || !Array.isArray(data)) return;

  const gaugeItem = gaugeList.value.find((item) => item.key === type);
  if (gaugeItem) {
    data.forEach((item, index) => {
      if (gaugeItem.data[index] && item.key === gaugeItem.data[index].key) {
        gaugeItem.data[index].value = item.value;
      }
    });
  }
};

// 监听topInfo.left变化
watch(
  () => props.topInfo?.left,
  (newVal) => {
    if (newVal) {
      processAssetTypeData(newVal);
      // 重新渲染图表
      nextTick(() => {
        renderCharts();
      });
    }
  },
  { immediate: true, deep: true }
);

// 监听topInfo.right变化
watch(
  () => props.topInfo?.right,
  (newVal) => {
    if (newVal) {
      // 处理合同合规预警数据
      if (newVal.ht) {
        processWarningData(newVal.ht, "contract");
      }
      // 处理空置监测预警数据
      if (newVal.kz) {
        processWarningData(newVal.kz, "vacancy");
      }
      // 处理价格比对预警数据
      if (newVal.price) {
        processWarningData(newVal.price, "rental");
      }
      // 处理文件缺失分析数据
      if (newVal.file) {
        processWarningData(newVal.file, "file");
      }
      // 重新渲染图表
      nextTick(() => {
        renderCharts();
      });
    }
  },
  { immediate: true, deep: true }
);

// 渲染图表函数
const renderCharts = () => {
  // 左侧大圆环
  if (bigPieRef.value) {
    const chart = echarts.init(bigPieRef.value);
    chart.setOption(
      getPieOption(
        assetPieData,
        true,
        `资产总数\n${assetData.totalAssets}`,
        colorArr
      )
    );
    window.addEventListener("resize", () => chart.resize());
  }
  // 右侧4个小圆环
  gaugeList.value.forEach((g) => {
    const chart = echarts.init(gaugeRefs[g.key]);
    chart.setOption(getPieOption(g.data, false, "", colorArr));
    window.addEventListener("resize", () => chart.resize());
  });
};

onMounted(() => {
  nextTick(() => {
    renderCharts();
  });
});
</script>

<style lang="scss" scoped>
.asset-overview-layout {
  display: flex;
  gap: 12px;
  align-items: stretch;
  height: 100%;
  .overview-left {
    height: 100%;
    display: flex;
    flex-direction: column;
    flex: 0.8;
  }
  .overview-right {
    height: 100%;
    display: flex;
    flex-direction: column;
    flex: 2.5;
  }
  .overview-left {
    .overview-item.total-assets {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
      padding: 16px 0 0 0;
      position: relative;
      .title {
        color: #222;
        font-size: 16px;
        font-weight: 700;
        margin-bottom: 8px;
        position: absolute;
        left: 24px;
        top: 16px;
        margin-left: 0;
        align-self: unset;
      }
      .big-pie-chart {
        width: 280px;
        height: 280px;
        margin: 0 auto;
        position: relative;
      }
      .big-pie-legend {
        display: flex;
        flex-direction: column;
        gap: 4px;
        margin-top: 16px;
        .legend-row {
          display: flex;
          justify-content: center;
          gap: 24px;
        }
        .legend-item {
          font-size: 14px;
          color: #666;
          display: flex;
          align-items: center;
          .legend-dot {
            display: inline-block;
            width: 16px;
            height: 8px;
            border-radius: 2px;
            margin-right: 6px;
          }
        }
      }
    }
  }
  .overview-right {
    .overview-grid {
      height: 100%;
      min-height: 340px;
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-template-rows: 1fr 1fr;
      gap: 12px;
      .overview-item.gauge {
        min-height: 0;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        padding: 8px 0 0 0;
        position: relative;
        .title {
          color: #222;
          font-size: 15px;
          font-weight: 700;
          position: absolute;
          left: 16px;
          top: 12px;
          margin-bottom: 0;
          z-index: 2;
        }
        .gauge-chart {
          width: 170px;
          height: 170px;
          margin: 0 auto;
          margin-top: 16px;
        }
        .gauge-legend {
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          gap: 8px;
          position: absolute;
          right: 16px;
          top: 50%;
          transform: translateY(-50%);
          margin-top: 0;
          .legend-item {
            font-size: 13px;
            color: #666;
            display: flex;
            align-items: center;
            .legend-dot {
              display: inline-block;
              width: 16px;
              height: 8px;
              border-radius: 2px;
              margin-right: 6px;
            }
          }
        }
      }
    }
  }
}
</style>
